/**
 * 常用JS变量:
 * agentEvent = 代理模式下自动点击模块
 * acEvent= 无障碍模式下自动点击模块
 * device = 设备信息模块
 * file = 文件处理模块
 * http = HTTP网络请求模块
 * shell = shell命令模块
 * thread= 多线程模块
 * image = 图色查找模块
 * utils= 工具类模块
 * global = 全局快捷方式模块
 * 常用java变量：
 *  context : Android的Context对象
 *  javaLoader : java的类加载器对象
 * 导入Java类或者包：
 *  importClass(类名) = 导入java类
 *      例如: importClass(java.io.File) 导入java的 File 类
 *  importPackage(包名) =导入java包名下的所有类
 *      例如: importPackage(java.util) 导入java.util下的类
 *
 */

// 淘宝App 包名
const PACKAGE_NAME = "com.taobao.taobao";
// 登录页
const LOGIN_ACTIVITY = "com.ali.user.mobile.login.ui.UserLoginActivity";
//主页面
const MAIN_ACTIVITY = "com.taobao.tao.TBMainActivity";
// 订阅店铺列表页面
const WEEX_ACTIVITY = "com.taobao.weex.WXActivity";
// 店铺主页面
const TAO_TRIVER_ACTIVITY = "com.alibaba.triver.container.TriverMainActivity";
// 直播间页面
const TAO_LIVE_VIDEO_ACTIVITY = "com.taobao.taolive.room.TaoLiveVideoActivity";
// 欢迎页面
const TAO_WELCOME_ACTIVITY = "com.taobao.tao.welcome.Welcome";


let executeCount = 0;

let GLOBAL_CONFIG = null;

const FLOAT_TAG = "xljx";

let floatTextView = null;

function main() {
    // 清除所有日志
    clearLog(-1);
    executeCount = ui.getShareData("currentCount") || 0;
    // 打印日志行号
    setFloatDisplayLineNumber(true);

    addEventCallback();

    logd("同步配置参数...");
    GLOBAL_CONFIG = {
        storeName: readConfigString("storeName"), // ui.getConfig("storeName"),
        loopCount: readConfigInt("loopCount"), //ui.getConfig("loopCount"),
        delaySwitch: readConfigBoolean("delaySwitch"), // ui.getConfig("delaySwitch"),
        delayTime: readConfigInt("delayTime"), // ui.getConfig("delayTime"),
        logSwitch: readConfigBoolean("logSwitch") // ui.getConfig("logSwitch")
    };
    // showExecuteFlag(); // fixme: 影响脚本异常后重新执行过程： 顶部Activity 查询错误！！！

    const saveBattery = device.getBattery();
    logd("当前电量：" + saveBattery + "%");
    if(saveBattery <= 20){
        toast('电池电量不足');
        device.vibrate(300);
    }

    logd("保持屏幕常量");
    keepScreenOn();

    if(!utils.isAppExist(PACKAGE_NAME)){
        toast("手机淘宝App 未安装！！！");
        releaseScript();
        return;
    }

    // todo: 自动化执行环境验证存在问题！
    if (!autoServiceStart(3)) {
        loge("自动化服务启动失败，无法执行脚本");
        releaseScript();
        return;
    }

    logd("开始执行脚本");
    logd("切换至桌面");
    home();
    sleep(120);
    logi("切换至'手机淘宝'App...");
    toast("如果长时间未切换至手机淘宝App,请手动打开手淘！");
    // if(!utils.openAppByName("手机淘宝")){
    if(!utils.openApp(PACKAGE_NAME)){
        toast("打开'手机淘宝'App失败");
        loge("打开'手机淘宝'App失败");
        showAlertStopDialog();
        return;
    }

    // if(!waitExistActivity(TAO_WELCOME_ACTIVITY, 10000)){
    //     toast("手机淘宝启动缓慢!!!");
    // }

    let currentCount = 0;
    const maxCount = 20; // 最大等待时间10s
    while(true){
        sleep(500);
        currentCount++;
        if(getRunningPkg() === PACKAGE_NAME){
            logd("正确打开了'手机淘宝'App");
            openTargetAppAfter();
            return;
        }
        
        if(currentCount >= maxCount){
            showAlertStopDialog();
        }
    }
}

/**
 * 打开目标App后
 */
function openTargetAppAfter(){
    if(TAO_WELCOME_ACTIVITY === getRunningActivity()){
        console.log("1");
        sleep(120);
        openTargetAppAfter();
        // fixme: 是否需要超时时间
    } else if(PACKAGE_NAME === getRunningPkg()){ // 只有上一步切换至桌面后，这里的验证才是完全可靠的！！！
        autoCorrectPage();
    } else {
        showAlertStopDialog();
    }
}

/**
 * 打开目标App后更正页面位置
 * fixme: 某些页面在特殊情况下调用back()无效！！！
 */
function autoCorrectPage(){
    console.log("autoCorrectPage---");
    const MAX_BACK_COUNT = 25;
    let currentBackCount = 0;
    while(true){
        currentBackCount++;
        if(currentBackCount > MAX_BACK_COUNT){
            showAlertStopDialog();
            return;
        }

        if(waitExistActivity(MAIN_ACTIVITY, 200)){
            logi("#正常进入主页面");
            nextStep();
            return;
        } else if(waitExistActivity(WEEX_ACTIVITY, 200)){
            console.log("#打开手机淘宝App位于" + WEEX_ACTIVITY);
            switchWeexSearchPage();
            return;
        } else if(waitExistActivity(TAO_TRIVER_ACTIVITY, 200)){
            // todo: 校验店铺是否为目标店铺
            correctTriverMainActivityFragmentIndex();
            const storeTitleSelector = clz("android.view.View").text(GLOBAL_CONFIG.storeName);
            if(waitExistNode(storeTitleSelector, 200)){
                logd('位于目标店铺主页面');
                // 处于店铺主页面
                liveTask();
                return;
            } else {
                logw('非目标店铺主页面！！！');
                back();
                sleep(320);
            }
        } else if(waitExistActivity(TAO_LIVE_VIDEO_ACTIVITY, 200)){
            autoExitLiveVideo();
        } else {
            back();
            sleep(320);
        }
    }
}

function nextStep(){
    // todo: 检测广告炫富层，并关闭
    const extAdFloatViewSelector = desc("浮层关闭按钮");
    if(extAdFloatViewSelector){
        click(extAdFloatViewSelector);
        sleep(120);
    }

    // 1. 处理页面内fragment页面
    // const homeTab1Selector = desc("首页");
    // const homeTab2Selector = desc(" 逛逛");
    // const homeTab3Selector = desc(" 消息");
    // const homeTab4Selector = desc(" 购物车");
    logd("切换tab至个人中心");
    const homeTab5Selector = clz("android.widget.FrameLayout").desc("我的淘宝").depth(8).drawingOrder(1);
    // console.log("主页面tab 状态：", homeTab1Selector, homeTab2Selector, homeTab3Selector, homeTab4Selector, homeTab5Selector);
    click(homeTab5Selector);

    // 2.验证是否登录
    if(waitExistActivity(LOGIN_ACTIVITY, 1200)){ // 时间不能过短
        toast("请先登录， 完成后再次手动运行脚本！！！");
        releaseScript();
        return;
    }

    logd("点击'订阅店铺'");
    const subscribeBtnSelector = clz("android.widget.LinearLayout").desc("订阅店铺").depth(12).drawingOrder(4);
    click(subscribeBtnSelector);
    sleep(600);
    if(!waitExistActivity(WEEX_ACTIVITY, 8* 1000)){
        toast("打开'订阅店铺'超时");
        showAlertStopDialog();
        return;
    }

    switchWeexSearchPage();
}

// function OpenTaobaoAppNext(){
//     let livePwd = readConfigString("livePwd");
//     let r = utils.setClipboardText(livePwd);
//     logd("淘口令：", livePwd);
// }

function autoServiceStart(time) {
    for (let i = 0; i < time; i++) {
        if (isServiceOk()) {
            return true;
        }
        let started = startEnv();
        logd("第" + (i + 1) + "次启动服务结果: " + started);
        if (isServiceOk()) {
            return true;
        }
    }
    return isServiceOk();
}

/**
 * 直播任务
 */
function liveTask(){
    console.log("liveTask---");
    if(executeCount >= GLOBAL_CONFIG.loopCount){
        console.log("-----------------");
        showTaskOverDialog();
        return;
    }

    // 更新悬浮窗日志
    if(!GLOBAL_CONFIG.logSwitch && floatTextView){
        floatTextView.setText("第" + (executeCount + 1) + "次进入直播间");
    }

    // const mainContentFlagSelector = clz("android.view.View").desc("店铺直播");
    // if(!waitExistNode(mainContentFlagSelector, 8 * 1000)){
    //     showAlertStopDialog();
    //     console.log("‘店铺直播’控件查询失败！！！");
    //     return;
    // }

    // 旧版本
    let loopCount = 0;
    const MAX_LOOP_COUNT = 10;
    while(true){
        loopCount++;
        console.log("-----------------2");
        // 点击白色背景的“立即观看”按钮
        let loopUkViewSelector = clz("android.view.View").desc("立即观看").depth(23).drawingOrder(1);
        if(waitExistNode(loopUkViewSelector, 200)){
            console.log("-----------------3");
            logd("进入直播间...");
            let lookupBtn = loopUkViewSelector.getOneNodeInfo(20).parent();
            const openResult = lookupBtn.click();
            console.log("点击立即观看结果:", openResult, "clickable:", lookupBtn.clickable);
            click(clz("android.widget.FrameLayout").depth(22).drawingOrder(1));
            break;
        } else {
            console.log("-----------------4");
            // 点击"立即观看"图片
            loopUkViewSelector = clz("android.widget.ImageView").depth(23).drawingOrder(1);
            if(waitExistNode(loopUkViewSelector, 200)){
                console.log("----------------5");
                // click(loopUkViewSelector); // ### 实际测试点击无效 ###
                // break;
                try{
                    loopUkViewSelector.getOneNodeInfo(600).parent().parent().parent().click(); // 点击的为整个视频大布局（半透明view）
                    break;
                } catch (e){
                    if(loopCount < MAX_LOOP_COUNT){
                        sleep(300);
                    } else {
                        showAlertStopDialog();
                        return;
                    }
                } finally {}
            } else {
                console.log("-----------------6");
                if(loopCount < MAX_LOOP_COUNT){
                    sleep(300);
                } else {
                    showAlertStopDialog();
                    return;
                }
            }
        }
    }

    if(!waitExistActivity(TAO_LIVE_VIDEO_ACTIVITY, 3200)){
        toast("打开直播间超时,请手动返回至上一个页面！！！");
        showAlertStopDialog();
        return;
    }


    // 计算直播间内等待时长
    let waitIntervalTime = null;
    if(GLOBAL_CONFIG.delaySwitch){
        waitIntervalTime = GLOBAL_CONFIG.delayTime * 1000;
    } else {
        waitIntervalTime = 10 * 1000 + random(1, 8) * 1000 + random(0, 2) * 1000;
    }
    // if(!GLOBAL_CONFIG.logSwitch){
    //     toast("直播间停留时间：" + waitIntervalTime + "ms");
    // }
    console.log("直播间等待执行时间：", waitIntervalTime);
    sleep(waitIntervalTime); // 直播间停留时间

    autoExitLiveVideo();

    if(!waitExistActivity(TAO_TRIVER_ACTIVITY, 600)){
        return;
    }

    executeCount++;
    // 记录上次执行次数
    let result = ui.putShareData("historyCount", executeCount);
    console.log("result: ", result);
    ui.putShareData("currentCount", executeCount);
    loop(pauseTime());
}

/**
 * 循环执行任务
 * @param intervalTime
 */
function loop(intervalTime){
    if(executeCount < GLOBAL_CONFIG.loopCount){
        sleep(intervalTime);
        // console.log("准备执行第" + (executeCount + 1) + "次");
        toast("准备执行第" + (executeCount + 1) + "次");
        liveTask();
    } else {
        showTaskOverDialog();
        logd("脚本执行完成");
    }
}

/**
 * 进入直播间的延迟时间
 * @returns {number}
 */
function pauseTime(){
    return 0;
}

function releaseScript(){
    device.cancelKeepingAwake();
    cancelObserveEvent("activity-change");
    if(GLOBAL_CONFIG.logSwitch){
        closeLogWindow();
    } else {
        floaty.close(FLOAT_TAG);
    }
    exit();
    // https://easyclick.gitee.io/docs/#/zh-cn/funcs/global/global?id=restartscript-%e9%87%8d%e5%90%af%e8%84%9a%e6%9c%ac
}

function addEventCallback(){
    observeEvent("activity-change",function (key,data){
        console.debug("页面切换: "+data);
    });
    setExceptionCallback((msg) => {
        loge(" 异常停止消息: "+msg);
        executeCount = ui.getShareData("currentCount");
        restartScript(null,true,1);
    });
}

/**
 * 切换至后台手机淘宝App后，位于Weex 页面；
 */
function switchWeexSearchPage(){
    const cancelBtnSelector = clz("android.view.View").desc("取消").depth(13).drawingOrder(1);
    if(waitExistNode(cancelBtnSelector, 120)){
        logd("已经位于搜索状态下");
        autoQueryTargetStore();
    } else {
        // desc("全部"); desc("店铺"); desc("其他");
        const topMenuNode = id("com.taobao.taobao:id/weex_render_view").getOneNodeInfo(200).allChildren()[0]
            .allChildren()[0].allChildren()[0];
        topMenuNode.allChildren()[topMenuNode.allChildren().length - 1].click();
        logd("准备搜索...");
        sleep(320);
        switchWeexSearchPage();
    }
}

/**
 * 自动搜索目标店铺
 */
function autoQueryTargetStore(){
    inputText(clz("android.widget.EditText"), GLOBAL_CONFIG.storeName);

    // 需要区分“搜索历史”中店铺名称与RecyclerView（两者均为des查询存在异议！）
    // const queryResultRecyclerViewSelector = clz("android.support.v7.widget.RecyclerView").depth(13).drawingOrder(1);
    if(waitExistNode(descMatch("订阅"), 4000)){ // 超时时间设置超大值，避免网络问题
        console.log('界面已显示查询结果');
        const targetItemTitleSelector = desc(GLOBAL_CONFIG.storeName);
        sleep(200);
        if(waitExistNode(targetItemTitleSelector, 3000)){
            logd("搜索成功，准备进入店铺主页面");
            click(targetItemTitleSelector);
            if(!waitExistActivity(TAO_TRIVER_ACTIVITY, 5000)){ // 进入此页面缓慢
                toast("进入店铺主页面等待超时3s！");
                showQueryStoreFailDialog();
            } else {
                liveTask();
            }
        } else {
            console.log("无有效的查询结果");
            showQueryStoreFailDialog();
        }
    } else {
        console.log("无有效的查询结果");
        showQueryStoreFailDialog();
    }
}

/**
 * 将店铺主页面切换至正确页面的fragment
 */
function correctTriverMainActivityFragmentIndex(){
    if(!waitExistNode(text("首页"), 120)){
        showAlertStopDialog();
        return;
    }

    click(text("首页"));

    if(!waitExistNode(text("推荐"), 120)){
        showAlertStopDialog();
        return;
    }

    // text("推荐").getOneNodeInfo(120).
    swipeToPoint(device.getScreenWidth(), device.getScreenHeight() / 2, 20, device.getScreenHeight() / 2, 200);
    sleep(580);
}

function showExecuteFlag(){
    // 显示实时日志悬浮窗
    if(hasFloatViewPermission()){
        if(GLOBAL_CONFIG.logSwitch){
            showLogWindow();
        } else {
            const tag = "xljx";
            importPackage(android.widget);
            importPackage(android.graphics);
            floatTextView = new TextView(context);
            floatTextView.setText("🧐脚本执行中...");
            floatTextView.setTextColor(Color.parseColor("#008500"));
            floatTextView.setBackgroundColor(Color.parseColor("#ffffff"));
            let view = floaty.showFloatView(tag,floatTextView,100,100);
            floaty.focusable(tag, true);
        }
    }
    if(requestFloatViewPermission(10)){
        if(GLOBAL_CONFIG.logSwitch){
            showLogWindow();
        } else {

            importPackage(android.widget);
            importPackage(android.graphics);
            floatTextView = new TextView(context);
            floatTextView.setText("🧐脚本执行中... 结束自动消失");
            floatTextView.setTextColor(Color.parseColor("#008500"));
            floatTextView.setBackgroundColor(Color.parseColor("#ffffff"));
            let view = floaty.showFloatView(FLOAT_TAG, floatTextView,100,100);
            floaty.focusable(FLOAT_TAG, true);
        }
    }
}

/**
 * 自动退出直播间
 */
function autoExitLiveVideo(){
    logd("准备退出直播间...");
    const topRightMenuBlockSelector = clz("android.widget.LinearLayout").id("com.taobao.taobao:id/taolive_close_new_layout"); // .depth(5).drawingOrder(1);
    if(!waitExistNode(topRightMenuBlockSelector, 1600)){
        showAlertStopDialog();
        return;
    }
    console.log("11111111111");
    // console.warn("菜单按钮元素个数：", topRightMenuBlockSelector.childCount());
    const liveVideoPageTopMenus = topRightMenuBlockSelector.getOneNodeInfo(800).allChildren();
    // fixme: 空指针异常
    if(!liveVideoPageTopMenus){
        toast("退出直播间查询退出按钮失败,手动退出试试！！！");
        device.vibrate(100);
        sleep(200);
        showAlertStopDialog();
        return;
    }

    // clz("android.widget.ImageView").depth(6).drawingOrder(3);
    liveVideoPageTopMenus[liveVideoPageTopMenus.length - 1].click();


    if(!waitExistActivity(TAO_TRIVER_ACTIVITY, 5000)){
        console.log("222222222");
        if(waitExistNode(text("直接退出"), 5 * 1000)) { // waitExistNode(text("去领红包"), 3 * 1000)
            toast("发现弹窗自动处理中...");
            click(text("直接退出"));
        } else if(waitExistNode(id("com.taobao.taobao:id/ubee_dialog_close"), 2500)){
            console.log("3333333333");
            click(id("com.taobao.taobao:id/ubee_dialog_close"));
        } else if(waitExistNode(text("继续退出"), 5 * 1000)){
            console.log("44444444444");
            click(text("继续退出"));
        } else {
            showAlertStopDialog();
        }
    }
}

/**
 * UI 控件查询提示框
 */
function showAlertStopDialog(){
    // let p = {
    //     "title": "提示",
    //     "msg": "UI控件查询超时",
    //     "cancelable": false,
    //     "cancelText": "取消",
    //     "okText": "重启试试"
    // };
    // ui.alert(p,
    //     function (dialog, v) {
    //         logd("ok btn click  : ")
    //         //让对话消失掉
    //         dialog.doDismiss();
    //         restartScript(null, true, 1);
    //         return true;
    //     },
    //     function (dialog, v) {
    //         logd("cancel btn click ")
    //         //让对话消失掉
    //         dialog.doDismiss();
    //         releaseScript();
    //         return true;
    //     },
    //     function () {
    //         logd("mission btn click ")
    //         return true;
    //     });

    autoCloseUpdateDialog();
    toast("任务执行过程中遇到了问题，自动恢复中...");
    device.vibrate(200);
    sleep(1000);
    restartScript(null, true, 1);
}

/**
 * 显示任务完成提示框
 */
function showTaskOverDialog(){
    let p = {
        "title": "提示",
        "msg": "任务已完成，共进入直播间" + executeCount + "次",
        "cancelable": false,
        "cancelText": "退出",
        "okText": "重新执行"
    };
    ui.alert(p,
        function (dialog, v) {
            logd("ok btn click  : ")
            //让对话消失掉
            dialog.doDismiss();
            device.cancelVibration();
            ui.putShareData("currentCount", 0);
            restartScript(null, true, 1);
            return true;
        },
        function (dialog, v) {
            logd("cancel btn click ")
            //让对话消失掉
            dialog.doDismiss();
            device.cancelVibration();
            releaseScript();
            return true;
        },
        function () {
            logd("mission btn click ")
            return true;
        });

    device.vibrate(2600);
    sleep(1200);
    device.vibrate(2600);
    sleep(1200);
    device.vibrate(2600);
}

/**
 * 显示查询店铺失败对话框
 */
function showQueryStoreFailDialog(){
    utils.setClipboardText(GLOBAL_CONFIG.storeName);
    const p = {
        "title": "搜索提示",
        "msg": "未查询到店铺‘" + GLOBAL_CONFIG.storeName + "’,请重新输入已关注的完整店铺名称：",
        "cancelable": false,
        "cancelText": "直接退出",
        "okText": "重启试试"
    };
    ui.inputDialog(p,
        function (dialog, v,text) {
            //text 是输入的文字
            logd("ok btn click  : "+text);
            ui.saveConfig("storeName", text);
            //让对话消失掉
            dialog.doDismiss();
            ui.putShareData("currentCount", 0);
            restartScript(null,true,1);
            return true;
        },
        function (dialog, v,text) {
            logd("cancel btn click "+text)
            //让对话消失掉
            dialog.doDismiss();
            releaseScript();
            return true;
        },
        function () {
            logd("### 错误弹窗已关闭");
            return true;
        });


    blockScriptExit();
}

function blockScriptExit(){
    // 阻塞脚本退出
    while(true){
        sleep(1000);
    }
}

function keepScreenOn(){
    // 保持屏幕长亮
    device.keepScreenOn();
    // 保持设备唤醒
    importClass(android.os.PowerManager)
    device.keepAwake(PowerManager.SCREEN_DIM_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP);
    device.keepScreenDim();
}

/**
 * 自动关闭升级提示框
 */
function autoCloseUpdateDialog(){
    // toast("尝试自动关闭升级/广告弹窗....");
    // clz("android.widget.RelativeLayout").id("com.taobao.taobao:id/update_contentDialog").depth(4).drawingOrder(1);
    const updateCancelBtnSelector = clz("android.widget.RelativeLayout").id("com.taobao.taobao:id/update_button_cancel");
    if(waitExistNode(updateCancelBtnSelector, 220)){
        click(updateCancelBtnSelector);
        sleep(100);
    }

    const extAdFloatViewSelector = desc("浮层关闭按钮");
    if(waitExistNode(extAdFloatViewSelector, 220)){
        click(extAdFloatViewSelector);
        sleep(120);
    }
}

main();
